<template>
  <div class="users-page">
    <!-- 搜索表单 -->
    <el-card class="search-form">
      <el-form :model="searchForm" :inline="true" class="search-form-content">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="selectedUsers.length === 0">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 用户表格 -->
    <el-card class="table-container">
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'primary'">
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="info" size="small" @click="viewUser(scope.row)">查看</el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="80px"
        class="dialog-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Users',
  data() {
    return {
      loading: false,
      searchForm: {
        username: '',
        email: '',
        status: ''
      },
      tableData: [],
      selectedUsers: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      userForm: {
        id: null,
        username: '',
        email: '',
        phone: '',
        role: 'user',
        status: 1
      },
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.loadUsers()
  },
  methods: {
    // 加载用户数据
    loadUsers() {
      this.loading = true
      // 模拟API调用
      setTimeout(() => {
        this.tableData = this.generateMockData()
        this.total = 156
        this.loading = false
      }, 500)
    },
    
    // 生成模拟数据
    generateMockData() {
      const data = []
      const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']
      const domains = ['qq.com', '163.com', 'gmail.com', 'sina.com']
      
      for (let i = 1; i <= this.pageSize; i++) {
        const id = (this.currentPage - 1) * this.pageSize + i
        const name = names[Math.floor(Math.random() * names.length)]
        const domain = domains[Math.floor(Math.random() * domains.length)]
        
        data.push({
          id,
          username: `${name}${id}`,
          email: `user${id}@${domain}`,
          phone: `138${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
          role: Math.random() > 0.8 ? 'admin' : 'user',
          status: Math.random() > 0.2 ? 1 : 0,
          createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toLocaleString()
        })
      }
      return data
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadUsers()
      ElMessage.success('搜索完成')
    },
    
    // 重置搜索
    handleReset() {
      this.searchForm = {
        username: '',
        email: '',
        status: ''
      }
      this.currentPage = 1
      this.loadUsers()
    },
    
    // 新增用户
    handleAdd() {
      this.dialogTitle = '新增用户'
      this.isEdit = false
      this.userForm = {
        id: null,
        username: '',
        email: '',
        phone: '',
        role: 'user',
        status: 1
      }
      this.dialogVisible = true
    },
    
    // 查看用户
    viewUser(row) {
      this.$router.push({
        path: '/detail',
        query: {
          type: 'user',
          id: row.id,
          action: 'view'
        }
      })
    },
    
    // 编辑用户
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.isEdit = true
      this.userForm = { ...row }
      this.dialogVisible = true
    },
    
    // 删除用户
    handleDelete(row) {
      ElMessageBox.confirm(
        `确定要删除用户 "${row.username}" 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 模拟删除操作
        const index = this.tableData.findIndex(item => item.id === row.id)
        if (index > -1) {
          this.tableData.splice(index, 1)
          this.total--
        }
        ElMessage.success('删除成功')
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    },
    
    // 批量删除
    handleBatchDelete() {
      ElMessageBox.confirm(
        `确定要删除选中的 ${this.selectedUsers.length} 个用户吗？`,
        '批量删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 模拟批量删除操作
        this.selectedUsers.forEach(user => {
          const index = this.tableData.findIndex(item => item.id === user.id)
          if (index > -1) {
            this.tableData.splice(index, 1)
            this.total--
          }
        })
        this.selectedUsers = []
        ElMessage.success('批量删除成功')
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    },
    
    // 表格选择变化
    handleSelectionChange(selection) {
      this.selectedUsers = selection
    },
    
    // 分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadUsers()
    },
    
    // 当前页变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadUsers()
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.userFormRef.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            // 编辑用户
            const index = this.tableData.findIndex(item => item.id === this.userForm.id)
            if (index > -1) {
              this.tableData[index] = { ...this.userForm }
            }
            ElMessage.success('编辑成功')
          } else {
            // 新增用户
            const newUser = {
              ...this.userForm,
              id: Date.now(),
              createTime: new Date().toLocaleString()
            }
            this.tableData.unshift(newUser)
            this.total++
            ElMessage.success('新增成功')
          }
          this.dialogVisible = false
        }
      })
    },
    
    // 对话框关闭
    handleDialogClose() {
      this.$refs.userFormRef?.resetFields()
    }
  }
}
</script>

<style scoped>
.users-page {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.search-form-content {
  margin: 0;
}

.operation-buttons {
  margin-bottom: 20px;
}

.table-container {
  background: white;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-form .el-form-item {
  margin-bottom: 20px;
}
</style>